﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;


namespace Jw.Utils
{
    /// <summary>
    /// C#自动计算字符串公式的值
    /// </summary>
    public class CalcStringExpression
    {
        /// <summary>
        /// 最简单的方式由SQL计算
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns></returns>
        public static float CalcBySQL(string expression)
        {
            string SQL = "SELECT " + expression + " AS RESULT_VALUE";
            SqlConnection conn = new SqlConnection("自己定义连接字符串");
            SqlCommand cmd = new SqlCommand(SQL, conn);
            object o = cmd.ExecuteScalar(); //执行SQL.
            return float.Parse(o.ToString());
        }

        /// <summary>
        ///  由Microsoft.Eval对象计算表达式，需要引用Microsoft.JScript和Microsoft.Vsa名字空间。
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns></returns>
        public static float CalcByJs(string expression)
        {
            try
            {
                float f = 0.0f;
                if (!string.IsNullOrWhiteSpace(expression) && !expression.Contains("Calc"))
                {
                    Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
                    object returnValue = Microsoft.JScript.Eval.JScriptEvaluate((object)expression, ve);
                    //被0除 无穷大
                    if (returnValue.ToString() == "正无穷大" || returnValue.ToString() == "负无穷大" || returnValue.ToString() =="非数字")
                    {
                        return 0;
                    }
                    f = float.Parse(returnValue.ToString());

                }
                return f;
            }
            catch
            {
                return 0;
            }
        }


    }
}
